package com.spontaneappnew.activities;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.graphics.PorterDuff;

import com.spontaneappnew.R;

public class NewPlaceImagesActivity extends Activity {

	public static final int MEDIA_TYPE_IMAGE = 1; 
    // directory name to store captured images and videos
    private static final String IMAGE_DIRECTORY_NAME = "SpontaneAPP";
	private Uri fileuri;
	private ImageView[] thumbnails;
    private ImageView currentImage;
    private int currentImageNum=-1;
    private ActionMode mActionMode;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_place_images);	
		
		thumbnails = new ImageView[6];
		thumbnails[0] = (ImageView) findViewById(R.id.thumb1);
		thumbnails[1] = (ImageView) findViewById(R.id.thumb2);
		thumbnails[2] = (ImageView) findViewById(R.id.thumb3);
		thumbnails[3] = (ImageView) findViewById(R.id.thumb4);
		thumbnails[4] = (ImageView) findViewById(R.id.thumb5);
		thumbnails[5] = (ImageView) findViewById(R.id.thumb6);
		
		OnClickListener lis = new OnClickListener() {
			
			@Override
			public void onClick(final View v) {
				if (mActionMode!=null){
					mActionMode.finish();
				} 
				currentImage = (ImageView) v;
        	    switch (v.getId()) {
				case R.id.thumb1:
				    currentImageNum=0;
					break;
				case R.id.thumb2:
				    currentImageNum=1;
					break;
				case R.id.thumb3:
				    currentImageNum=2;
					break;
				case R.id.thumb4:
				    currentImageNum=3;
					break;
				case R.id.thumb5:
				    currentImageNum=4;
					break;
				case R.id.thumb6:
				    currentImageNum=5;
					break;

				default:
					break;
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(NewPlaceImagesActivity.this);
				builder.setMessage(R.string.add_image_dialog_message)
			       .setTitle(R.string.add_image_dialog_title)
				   .setPositiveButton(R.string.add_image_dialog_take_photo, new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			    			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);      	   
			        	    fileuri = getOutputMediaFileUri(1);		        	 
			        	    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileuri);
			        	    startActivityForResult(intent, 123);
			           }
			       }) 
			      .setNegativeButton(R.string.add_image_dialog_choose_from_gallery, new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id)      { 
			    			Intent pickPhoto = new Intent(Intent.ACTION_PICK,
			        	           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			    			currentImage = (ImageView) v;
			    			startActivityForResult(pickPhoto , 124);
			           }
		       });
			   AlertDialog dialog = builder.create();
			   dialog.show();	
				
			}
		};
		
		OnLongClickListener longLis = new View.OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				currentImage = (ImageView) v;
				switch (v.getId()) {
				case R.id.thumb1:
				    currentImageNum=0;
					break;
				case R.id.thumb2:
				    currentImageNum=1;
					break;
				case R.id.thumb3:
				    currentImageNum=2;
					break;
				case R.id.thumb4:
				    currentImageNum=3;
					break;
				case R.id.thumb5:
				    currentImageNum=4;
					break;
				case R.id.thumb6:
				    currentImageNum=5;
					break;
				default:
					break;
				}
				if (mActionMode != null) {
		            return false;
		        }

		        // Start the CAB using the ActionMode.Callback defined above
		        mActionMode = NewPlaceImagesActivity.this.startActionMode(mActionModeCallback);
		        v.setSelected(true);
		        return true;
			}
		};
		
		OnTouchListener touchLis = new OnTouchListener() {
			@Override
	        public boolean onTouch(View v, MotionEvent event) {

	            switch (event.getAction()) {
	                case MotionEvent.ACTION_DOWN: {
	                    ImageView view = (ImageView) v;
	                    view.getDrawable().setColorFilter(0x7736B2E3, PorterDuff.Mode.SRC_ATOP);
	                    view.invalidate();
	                    break;
	                }
	                case MotionEvent.ACTION_UP:
	                case MotionEvent.ACTION_CANCEL: {
	                    ImageView view = (ImageView) v;
	                    view.getDrawable().clearColorFilter();
	                    view.invalidate();
	                    break;
	                }
	            }
	            return false;
			}

		};
	
		for (int i=0;i<6;i++){
			thumbnails[i].setOnClickListener(lis);
			thumbnails[i].setOnLongClickListener(longLis);
			thumbnails[i].setOnTouchListener(touchLis);
			if (AddNewPlaceActivity.imgsArray[i]!=null){
				thumbnails[i].setImageURI(AddNewPlaceActivity.imgsArray[i]);
			}		
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.new_place_images, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.action_new_place_images_done){
			finish();
			return true;
		} else 
			return super.onOptionsItemSelected(item);
	}

	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
		switch(requestCode) {
		case 123:
		    if(resultCode == RESULT_OK){
		    	galleryAddPic();
	            BitmapFactory.Options options = new BitmapFactory.Options();
	            options.inSampleSize = 8;
		    	final Bitmap bitmap = BitmapFactory.decodeFile(fileuri.getPath(),
	                    options);
		    	currentImage.setImageBitmap(bitmap);
		    	AddNewPlaceActivity.imgsArray[currentImageNum]=fileuri;
		    }
		break; 
		case 124:
		    if(resultCode == RESULT_OK){
		        Uri selectedImage = imageReturnedIntent.getData();
		        currentImage.setImageURI(selectedImage);
		        AddNewPlaceActivity.imgsArray[currentImageNum]=Uri.parse(convertMediaUriToPath(selectedImage));
		    }
		break;
	    default:
			break;
		}
	}

	private void galleryAddPic() {
	    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	    mediaScanIntent.setData(fileuri);
	    this.sendBroadcast(mediaScanIntent);
	}
	
	public Uri getOutputMediaFileUri(int type) {
	    return Uri.fromFile(getOutputMediaFile(type));
	}
	 
	/*
	 * returning image
	 */
	private static File getOutputMediaFile(int type) {
	    // External sdcard location
	    File mediaStorageDir = new File(Environment
	                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
	            IMAGE_DIRECTORY_NAME);
	 
	    // Create the storage directory if it does not exist
	    if (!mediaStorageDir.exists()) {
	        if (!mediaStorageDir.mkdirs()) {
	            return null;
	        }
	    }
	 
	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
	            Locale.getDefault()).format(new Date());
	    File mediaFile;
	    if (type == MEDIA_TYPE_IMAGE) {
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator
	                + "IMG_" + timeStamp + ".jpg");
	    } else {
	        return null;
	    }
	 
	    return mediaFile;
	}
	
	private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
		
		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			 switch (item.getItemId()) {
	         case R.id.action_delete_image_done:
	        	 currentImage.setImageResource(R.drawable.ic_plus_image);
	        	 AddNewPlaceActivity.imgsArray[currentImageNum]=null;
	             mode.finish(); // Action picked, so close the CAB
	             return true;
	         default:
	             return false;
			 }
		}
	
	
		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			 MenuInflater inflater = mode.getMenuInflater();
		     inflater.inflate(R.menu.images_context_menu, menu);
		     return true;
		}
	
		@Override
		public void onDestroyActionMode(ActionMode arg0) {
			mActionMode = null;
			
		}
	
		@Override
		public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
			return false;
		}
	
	};
	
	protected String convertMediaUriToPath(Uri uri) {
	    String [] proj={MediaStore.Images.Media.DATA};
	    Cursor cursor = getContentResolver().query(uri, proj,  null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    String path = cursor.getString(column_index); 
	    cursor.close();
	    return path;
	}
}
